const fs = require("fs");
const path = require("path");
const config = require("./config.js")
/**
 * 卸载生成的模块
 *
 * @param {*} moduleName
 * @param {*} dirname
 */
const unloadResource = (moduleName, dirname) => {
	const viewsPath = path.join(dirname, config.rootPath, config.viewPath, moduleName);
	const apiPath = path.join(dirname, config.rootPath, config.apiPath, moduleName + '.' + config.lang);
	rmdir(viewsPath);
	rmdir(apiPath);
	console.log(moduleName + " unload succeeded!");
};

function rmdir(filePath, callback = () => {}) {
	// 先判断当前filePath的类型(文件还是文件夹,如果是文件直接删除, 如果是文件夹, 去取当前文件夹下的内容, 拿到每一个递归)
	fs.stat(filePath, function (err, stat) {
		if (err) return console.log(err);
		if (stat.isFile()) {
			fs.unlink(filePath, callback);
		} else {
			fs.readdir(filePath, function (err, data) {
				if (err) return console.log(err);
				let dirs = data.map(dir => path.join(filePath, dir));
				let index = 0;
				!(function next() {
					// 此处递归删除掉所有子文件 后删除当前 文件夹
					if (index === dirs.length) {
						fs.rmdir(filePath, callback);
					} else {
						rmdir(dirs[index++], next);
					}
				})();
			});
		}
	});
}

module.exports = unloadResource;
